﻿using System;
using System.Collections.Generic; 
using System.IO; 

namespace Helpers
{
    /* 
    * 2018年8月30日16:57:03
    * 调用方式：
    * LogHelper.SaveLog("Login", LogHelper.LogType.Login, "192.168.1.150");
    */
    public class LogHelper
    {
        //public static Dictionary<string, string> Logowner = new Dictionary<string, string>();//日志对象集合
        public static Dictionary<LogType, Dictionary<string, string>> Logtype = new Dictionary<LogType, Dictionary<string, string>>();//日志对象集合
        public static string LogPath
        {
            get
            {
                return AppDomain.CurrentDomain.BaseDirectory + @"\Log" + @"\" + DateTime.Now.ToString("yyyy_MM_dd");
            }
        }

        /// <summary>
        /// 日志类型
        /// </summary>
        public enum LogType
        {
            [System.ComponentModel.Description("通讯")]
            Socket,
            [System.ComponentModel.Description("账户相关")]
            User,
            [System.ComponentModel.Description("软件操作")]
            SystemOperation,
            [System.ComponentModel.Description("任务逻辑")]
            Task,
            [System.ComponentModel.Description("接收的原始数据")]
            OriginalReceive,
            [System.ComponentModel.Description("发送的原始数据")]
            OriginalSend,
            [System.ComponentModel.Description("AGV读取到的地标")]
            AGV_Location,
            [System.ComponentModel.Description("AGV的电压")]
            AGV_Voltage,
            [System.ComponentModel.Description("AGV的异常")]
            AGV_Error,
            [System.ComponentModel.Description("充电相关")]
            Charging,
            [System.ComponentModel.Description("电梯相关")]
            Elevator,
            [System.ComponentModel.Description("自动门相关")]
            AutoDoor,
            [System.ComponentModel.Description("呼叫盒相关")]
            Callbox,
            [System.ComponentModel.Description("异常信息")]
            ErrorInfo,
            [System.ComponentModel.Description("AGV运行指令")]
            AGV_RFID_Action,
            [System.ComponentModel.Description("交管")]
            Crossing,
            [System.ComponentModel.Description("其他")]
            Other,
            [System.ComponentModel.Description("PLC")]
            PLC,
            [System.ComponentModel.Description("OnorOffline")]
            OnorOffline,
            [System.ComponentModel.Description("仙知接收数据状态")]
            RecDataState,
        }

        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="message">日志内容</param>
        /// <param name="logType">日志类型</param>
        /// <param name="owner">IP地址</param>
        public static void SaveLog(string message, LogType logType, string owner)
        {

            string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            if (string.IsNullOrEmpty(message))
                return;
            var path = string.Format(@"\{0}\", logType.ToString());
            WriteLog(path, message, owner, dt);

            //Dictionary<string, string> Logowner = new Dictionary<string, string>();
            //if (Logtype.Keys.Contains(logType))
            //{
            //    if (Logtype[logType].Keys.Contains(owner))
            //    {
            //        //if (Logtype[logType][owner] != message)
            //        //{ //重复日志内容不再记录
            //            Logtype[logType][owner] = message;
            //            if (ShenMaPrint.Properties.Settings.Default.SaveLogs)
            //            {
            //                string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //                if (string.IsNullOrEmpty(message))
            //                    return;
            //                var path = string.Format(@"\{0}\", logType.ToString());
            //                WriteLog(path, message, owner, dt);
            //            }
            //        //}
            //    }
            //    else
            //    {
            //        Logtype[logType].Add(owner, message);
            //        if (ShenMaPrint.Properties.Settings.Default.SaveLogs)
            //        {
            //            string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //            if (string.IsNullOrEmpty(message))
            //                return;
            //            var path = string.Format(@"\{0}\", logType.ToString());
            //            WriteLog(path, message, owner, dt);
            //        }
            //    }
            //}
            //else
            //{
            //    Logowner.Add(owner, message);
            //    Logtype.Add(logType, Logowner);
            //    if (ShenMaPrint.Properties.Settings.Default.SaveLogs)
            //    {
            //        string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            //        if (string.IsNullOrEmpty(message))
            //            return;
            //        var path = string.Format(@"\{0}\", logType.ToString());
            //        WriteLog(path, message, owner, dt);
            //    }
            //}

        }

        /// <summary>
        /// 执行写日志操作
        /// </summary>
        /// <param name="path"></param>
        /// <param name="message"></param>
        /// <param name="IP"></param>
        private static void WriteLog(string path, string message, string IP, string dt)
        {
            path = LogPath + path;
            var fileName = string.Format("{0}.log", IP);

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            using (FileStream fs = new FileStream(path + fileName, FileMode.Append, FileAccess.Write,
                                                  FileShare.Write, 1024, FileOptions.Asynchronous))
            {
                try
                {
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes("[" + dt + "]:" + message + "\r\n");
                    IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length,
                        (asyncResult) =>
                        {
                            var fStream = (FileStream)asyncResult.AsyncState;
                            fStream.EndWrite(asyncResult);
                        },

                        fs);
                    fs.Close();
                }
                catch (Exception e)
                {
                    LogHelper.SaveLog("thread WriteLog error..." + e.ToString() + "\r\n", LogHelper.LogType.ErrorInfo, "WriteLog");
                }
            }
            ////path = DateTime.Now.ToString("yyyy_MM_dd") + "\\" + path;
            ////var fileName = string.Format("{0}.log", IP);
            ////ILog logger = CustomRollingFileLogger.GetCustomLogger(fileName, path);
            ////logger.Debug(dt + ":" + message + "\r\n");

            //if (!Directory.Exists(path))
            //    Directory.CreateDirectory(path);
            ////log4net.LogManager.GetLogger();
            //using (FileStream fs = new FileStream(path + fileName, FileMode.Append, FileAccess.Write,
            //                                      FileShare.Write, 1024, FileOptions.Asynchronous))
            //{
            //    try
            //    {
            //        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(dt + ":" + message + "\r\n");
            //        IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length,
            //            (asyncResult) =>
            //            {
            //                var fStream = (FileStream)asyncResult.AsyncState;
            //                fStream.EndWrite(asyncResult);
            //            },

            //            fs);
            //        fs.Close();
            //    }
            //    catch (Exception)
            //    {
            //        fs.Close();

            //    }

            //}
        }
    }
}

